//
//  RssDetailViewController.m
//  RssRead
//
//  Created by 旺财 on 10-11-1.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "RssDetailViewController.h"
#import "OPMLViewController.h"


@implementation RssDetailViewController
@synthesize webv;
@synthesize con;
@synthesize row;
@synthesize count;
@synthesize list;
@synthesize pretouch;
@synthesize mytitle;
@synthesize isupdate;
@synthesize link;
@synthesize htmlstring;
@synthesize isloadweb;
@synthesize isfirstend;
@synthesize mybaritem1;
@synthesize myTabBar;



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	self.navigationController.delegate=self;
	webv.delegate=self;
	webv.scalesPageToFit = YES;
	[self initCustomBar];
	[self setIsupdate:@"NO"];
	self.count=[self.list count];
	[self go];
	[super viewDidLoad];
}

- (void) initCustomBar
{	
	 tools = [[UIView alloc]  initWithFrame:CGRectMake (0, 0, 80, 45)]; 
	[tools setAlpha:[self.navigationController.navigationBar alpha]]; 
	UIButton *anotherButton = [UIButton buttonWithType:100];
	UIButton *anotherButton1 = [UIButton buttonWithType:100];
	UIImage *x= [UIImage imageNamed:@"arrow_left.png"];
	UIImage *x1= [UIImage imageNamed:@"arrow_right.png"];
	anotherButton.frame= CGRectMake(0, 7.5f, 40, 30);
	anotherButton1.frame= CGRectMake(42, 7.5f, 40, 30);
	[anotherButton setImage:x forState:UIControlStateNormal];
	[anotherButton1 setImage:x1 forState:UIControlStateNormal];
	[anotherButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
	[anotherButton1 addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
	[tools insertSubview:anotherButton atIndex:0];	
	[tools insertSubview:anotherButton1 atIndex:1];	
	UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithCustomView:tools]; 
    self.navigationItem.rightBarButtonItem = myBtn;
	[tools release];
	//[anotherButton release];
	//[anotherButton1 release];
	//[x release];
	//[x1 release];
	[myBtn release]; 
}


- (void) changeTabbarItem
{
	UITabBarItem *item=[[myTabBar items] objectAtIndex:0];
	if (!isOpenRss) 
	{
		item.image=[UIImage imageNamed:@"tabrss.png"];
		item.title=@"查看RSS";
		item.tag=2;
		item.enabled=YES;
		
	}
	else {
		item.image=[UIImage imageNamed:@"web.png"];
		item.title=@"查看网页";
		item.tag=1;
		item.enabled=YES;
	}
	[myTabBar setSelectedItem:nil];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void) loadfromweb
{
	[self.webv loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.link]]];
	UITabBarItem *item=[[myTabBar items] objectAtIndex:0];
	item.image=[UIImage imageNamed:@"web.png"];
	item.title=@"查看网页";
	item.tag=1;
	isOpenRss=NO;

}

-(void) loadfromRss
{
	[self.webv loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
	UITabBarItem *item=[[myTabBar items] objectAtIndex:0];
	item.image=[UIImage imageNamed:@"tabrss.png"];
	item.title=@"查看RSS";
	item.tag=2;
	isOpenRss=YES;
	
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {

	if (myTabBar==nil)
	{
		myTabBar=tabBar;
	}
	
	if (item.tag==1)
	{
	    [self loadfromweb];
	}
	else if (item.tag==2)
	{
		[self loadfromRss];
	}
	else if(item.tag==3)
	{
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.link]];
	}
	
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated;
{
	if (![[viewController nibName] isEqualToString:@"RssDetailViewController" ])
	{
		OPMLViewController *tmp=(OPMLViewController *)viewController ;
		NSDate *mtime = [[[NSFileManager defaultManager] attributesOfItemAtPath:tmp.md5filename error:nil] fileCreationDate];
		[self.list writeToFile:tmp.md5filename atomically:YES];
		NSMutableDictionary *mDic =[[NSMutableDictionary alloc] init];
		[mDic setObject:mtime forKey:@"NSFileCreationDate"];
		[[NSFileManager defaultManager] setAttributes:mDic ofItemAtPath:tmp.md5filename error:nil ];
	    [mDic release];
		[webv release];
		[tools release];
		[myTabBar release]; 
		[toolbar release];
		[myAlert release];
		//[list release];
		//[super dealloc];
		[tmp setrootNode:[Common getrootE]];
		[tmp getOpmlOrRss:NO];
		[tmp.tableView reloadData];
		self.navigationController.delegate=tmp;
	}
}

-(void) initToolbar
{
	NSMutableArray *toolbarItems = [[NSMutableArray arrayWithArray:tools.subviews] retain];
	UIButton *barpre = [toolbarItems objectAtIndex:0];
	UIButton *barnext =[toolbarItems objectAtIndex:1];
	if (row==0)
	{
		barpre.enabled=NO;
	}
	else
	{
		barpre.enabled=YES;
	}
	if (row<count-1)
	{
		barnext.enabled=YES;
	}
	else 
	{
		barnext.enabled=NO;
	}
	[toolbarItems release];
	//[barpre release];
	//[barnext release];
}
-(void) go
{
	[self initToolbar];
	NSMutableDictionary * item=[[NSMutableDictionary alloc] initWithDictionary:[self.list objectAtIndex:row]];
	NSString *isread=[item objectForKey:@"isread"];
	if ([isread isEqualToString:@"no"]) 
	{
		
		[self setIsupdate:@"YES"];
	
		[item setObject:@"yes" forKey:@"isread"];
		[self.list replaceObjectAtIndex:row withObject:item];
	}
	NSString *tlink=[[NSString alloc] initWithString: [item objectForKey:@"link"]];
	self.link = [tlink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	[tlink release];
	self.htmlstring=[[NSString alloc] initWithFormat:@"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
	"<head>"
	"<meta name=\"viewport\" content=\"width=device-width\" />"
	"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />"
	"<style type=\"text/css\">"
	"<!--"
					 "div {" 
					 "table-layout: fixed;" 
					 "word-wrap: break-all;" 
					 //"width: 250px;" 
					 "overflow: hidden;" 
					 "}"
					 "img {" 
					 "max-width: 300px;" 
					 //"height:expression(this.width > 300 ? this.height*300/this.width : this.hight);"
					 "width:expression(this.width > 300 ? \"300px\" : this.width);"
					 "overflow:hidden;" 
					 "}" 
					 " .box {"
					 "-webkit-box-shadow: 3px 3px 6px #000;"
					 "-webkit-border-radius: 10px;"
					 "background: #5A7FE6;"
					"padding: 5px;"
					 "font-size: 19px; color: #FFFFFF; font-family: Arial, Helvetica, sans-serif;"
					 "}"
					 " .box1 {"
					 "padding: 5px;"
					 "text-align:right;"
					 "font-weight: bold; font-size: 12px; color: #7D9CF0; font-family: Arial, Helvetica, sans-serif;"
					 "}"
					 " .box2 {"
					 "padding: 5px;"
					 "font-weight: bold; font-size: 15px;"
					 "}"
	"-->"
	"</style>"
	"</head>"
					 "<body><div class=\"box\">%@<div class=\"box1\">%@</div></div>"
					 "<p><div>%@</div></p>"
	
	"</body>"
				
						  "</html>",[item objectForKey:@"title"],[item objectForKey:@"date"],[item objectForKey:@"summary"]];
	[item release];
	
	if ([Common getConfig].defaultOpenWithRss) 
	{
		[self loadfromRss];
	}
	else {
		[self loadfromweb];
	}

	//NSString *s=;
	self.title=[[NSString stringWithFormat :@"%d/%d",row+1,count] stringByAppendingString:self.mytitle];
	//= s;	
	
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    	NSString *requestString = [[request URL] absoluteString];
    NSLog(@"fuck");
	NSArray *components = [requestString componentsSeparatedByString:@":"];
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"myweb"]) 
	{
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"])
        {
			if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"end"])
			{
				if ([self.pretouch isEqualToString: @"start"])
				{
					[self.navigationController setNavigationBarHidden:NO animated:YES];
					[myTabBar setHidden:NO];
					webv.frame= CGRectMake(0, 0, 320, 411);
				}
				
			}
			else 
			{
				if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"]) 
				{
					if ([self.pretouch isEqualToString: @"move"])
					{
						[self.navigationController setNavigationBarHidden:YES animated:YES];
						[myTabBar setHidden:YES];
						webv.frame= CGRectMake(0, 0, 320, 460);
					}
					
				}
					[self setPretouch:[components objectAtIndex:2]];
			}
			        
		}
        return YES;
    }
    return YES;
}

-(IBAction) back:(id)sender
{
	row=row-1;
	[self go];
		
}
-(IBAction) next:(id)sender
{
	row=row+1;
	[self go];
}
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
        
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
	[[[myTabBar items] objectAtIndex:0] setEnabled:NO];

	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	[self changeTabbarItem];
		[self.webv stringByEvaluatingJavaScriptFromString:
		 @"var headID = document.getElementsByTagName(\"head\")[0];"    
		 "var newScript = document.createElement('script');"
		 "newScript.type = 'text/javascript';"
		 "newScript.text = 'document.ontouchstart=function(){          document.location=\"myweb:touch:start\";  }; document.ontouchend=function(){          document.location=\"myweb:touch:end\";  }; document.ontouchmove=function(){          document.location=\"myweb:touch:move\";  } ';"
		 "headID.appendChild(newScript);"];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	[self changeTabbarItem];
	
}

- (void)dealloc {
	[webv release];
	[tools release];
	[myTabBar release]; 
	[toolbar release];
    [myAlert release];
	[list release];
  //[super dealloc];
}


@end
